## Analysis and Figures/Tables Replication Script ##
## This file is pulling in the already cleaned datasets from the first RScript 
## run the RDD analysis and produce the tables and figures in the main paper and appendix

#  Load necessary packages ----
rm(list=ls())
library(data.table)
library(tools)
library(dplyr)
library(stargazer)
library(rdrobust)
library(xtable)
library(rddensity)
library(qdap)
library(readxl)
library(ggplot2)
library(gridExtra)
library(textclean)
library(sm)

# Set working directory ----
## Change working directory to your own
setwd("~/Dropbox (MIT)/RDD_stateleg/Replication Materials")

# Read in data ----
rddset <- read.csv("fullRDDdataset20182020_analysis.csv")

# Main Paper Figure and Table Replication ----

# Figure 1 ----
maindescplot <- rdplot(rddset$general2p, rddset$minorityprimarymargin, y.lim=c(0,1), x.label="Primary Win Margin for Minority Candidate", y.label="Two-party vote share in general election")
maindescplot <- maindescplot$rdplot + geom_point(rddset, mapping=aes(minorityprimarymargin,general2p), size=1.1, col="darkgray", alpha=.3)

pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Main Paper Tables and Figures/RDDplot_basic_201820combineddata_plusscatter.pdf")
maindescplot
dev.off()

# Table 1 ----
rdrobust(rddset[rddset$year.x==2020,]$general2p, rddset[rddset$year.x==2020,]$minorityprimarymargin)$coef

rddset$openseat <- ifelse(rddset$incumbentrunning==1, 0, 1);table(rddset$openseat) 

rddset$partyvotesharepres <- ifelse(rddset$party=="Democratic", rddset$Dem_2pyShare, 1-rddset$Dem_2pyShare);summary(rddset$partyvotesharepres)
rddset$safedist16 <- ifelse(rddset$partyvotesharepres>.6, 1, 0); table(rddset$safedist16)

basicrdd <- rdrobust(rddset$general2p, rddset$minorityprimarymargin)
basicrdd_covar <- rdrobust(rddset$general2p, rddset$minorityprimarymargin, covs=cbind(rddset$partyfac,rddset$openseat, rddset$Total.x, rddset$partyvotesharepres))
basicrddp3 <- rdrobust(rddset$general2p, rddset$minorityprimarymargin, p=3, covs=cbind(rddset$partyfac,rddset$openseat, rddset$Total.x, rddset$partyvotesharepres))
basicrdd_R1 <- rdrobust(rddset$general2p, rddset$minorityprimarymargin, h=.1,covs=cbind(rddset$partyfac,rddset$openseat, rddset$Total.x, rddset$partyvotesharepres))

summary(basicrdd)
summary(basicrdd_covar)
summary(basicrddp3)
summary(basicrdd_R1)

model1 <- c(round(basicrdd$coef[1], 2), paste("(",round(basicrdd$ci[3],2),",",round(basicrdd$ci[6],2), ")", sep=""), "p=1", "", sum(basicrdd$N_h), round(basicrdd$bws[1],2), "Auto")
model2 <- c(round(basicrdd_covar$coef[1],2), paste("(",round(basicrdd_covar$ci[3],2),",",round(basicrdd_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrdd_covar$N_h), round(basicrdd_covar$bws[1],2), "Auto")
model3 <- c(round(basicrddp3$coef[1],2), paste("(",round(basicrddp3$ci[3],2),",",round(basicrddp3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddp3$N_h), round(basicrddp3$bws[1],2),"Auto")
model4 <- c(round(basicrdd_R1$coef[1],2), paste("(",round(basicrdd_R1$ci[3],2),",",round(basicrdd_R1$ci[6],2), ")", sep=""), "p=1", "X",sum(basicrdd_R1$N_h), round(basicrdd_R1$bws[1],2),"Manual")

modtab <- cbind(model1, model2, model3, model4)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth", "Bandwidth Selection")

colnames(modtab) <- c("(1)","(2)","(3)","(4)")
print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare", label="mainRDtab", align="rcccc"), include.colnames=T, hline.after = c(0,2,7), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Main Paper Tables and Figures/simplemainRDtable_presvote_R1edits.tex")

# Appendix Figures and Tables Replication ----

# Figure A1 ----

# Note: extra data needed to create Figure A1
# Read in  district vote data
votedata <- read.csv("2016_PresBySLDist.csv") 
dim(votedata) # 4709 obs 10 vars 

votedata <- votedata[!(votedata$state %in% c("Florida", "Texas")),]; dim(votedata) # 4527 obs 10 vars

# make some naming changes so they'll line up with the main dataset
votedata[votedata$state=="Massachusetts", "district"] <- toupper(replace_ordinal(votedata[votedata$state=="Massachusetts", "district"]))
setDT(rddset)
rddset[state.y=="MA", uniquedist_noyear:= toupper(gsub("&", "and", gsub("-", "", substr(uniquedist, 6,nchar(uniquedist)))))]

#set up unique district labels that will match the main dataset for simpler merge
votedata$Upper <- ifelse(votedata$office=="State House", 0, 1); table(votedata$Upper); table(votedata$office)
votedata$uniquedist_noyear <- paste(votedata$state_postal, votedata$Upper, votedata$district, sep=" ") 

rddset_votes <- merge(rddset, votedata, by="uniquedist_noyear"); dim(rddset_votes); dim(rddset)

#create an indicator in the main vote dataset of which obs are in our RD set
votedata$rddset <- 0
votedata[votedata$uniquedist_noyear %in% rddset_votes$uniquedist_noyear, "rddset"] <- 1
table(votedata$rddset); dim(rddset_votes); length(unique(rddset_votes$uniquedist_noyear)) 
length(unique(rddset$uniquedist_noyear)) 

# Create Figure A1: Comparing RD sample districts to the rest of the US 
meansparty <- rddset[!(rddset$party=="Other"),] %>% group_by(party) %>% summarise_at(vars("pctWhite", "pctBlack", "pctLatino", "pctAsian"), mean)
meansparty18 <- rddset[rddset$year.x==2018,] %>% group_by(party) %>% summarise_at(vars("pctWhite", "pctBlack", "pctLatino", "pctAsian"), mean)
meansparty20 <- rddset[rddset$year.x==2020 & !(rddset$party=="Other"),] %>% group_by(party) %>% summarise_at(vars("pctWhite", "pctBlack", "pctLatino", "pctAsian"), mean)
meanspartybyyear <- rbind(meansparty18, meansparty20)
meanspartybyyear$year <- c(2018, 2018, 2020, 2020)

rddset$majmindist <- ifelse(rddset$pctWhite < .5, 1, 0) 
summary(rddset$majmindist) 

# Find tertiles
vTert = quantile(rddset$pctWhite, c(0:3/3))

# classify values
rddset$pctwhite_tert = with(rddset, 
                            cut(pctWhite, 
                                vTert, 
                                include.lowest = T, 
                                labels = c("PctWhiteBottomThird", "PctWhiteMiddleThird", "PctWhiteUpperThird")))

# plot data 
plot(density(rddset$Dem_2pyShare, na.rm=T))
plot(density(votedata$Dem_2pyShare, na.rm=T))
library(sm)
votedata <- na.omit(votedata); dim(votedata) 
pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/comparedensity_Dem2pyVoteshare2016.pdf")
sm.density.compare(votedata$Dem_2pyShare, votedata$rddset, xlab="Democratic 2-party Presidential Vote Share, 2016", 
                   col=c("dodgerblue4", "dodgerblue4"), lty=c(2,3))
title(main="Comparing districts in the RD sample to all districts")
legend("topright", legend = c("Rest of US","RDD Sample"), lty=c(2,3)) 
dev.off()

# Figure A2 ----

#### Note: This function is also needed to replicate Figure A4 ####
rdplotllfunc <- function(outcome, outcomealone, outcomename, plotname, ylims){ #make a plotting function to handle multiple covars
  rddmod <- rdrobust(outcome, rddset$minorityprimarymargin)
  print(rddmod$pv[3]) #also spit out the p-value while we're at it.
  outcomevar <- rlang::sym(outcomealone) #transform this so we can feed it to aes below
  print(outcomevar)
  bandwidth = rdrobust(outcome, rddset$minorityprimarymargin)$bws[1, 1]
  maindescplot <- rdplot(outcome[abs(rddset$minorityprimarymargin) <= bandwidth], rddset$minorityprimarymargin[abs(rddset$minorityprimarymargin) <= bandwidth],p = 1, kernel = "triangular", x.label = "Primary Win Margin for Minority Candidate", y.label=outcomename, title=plotname, y.lim=ylims)
  maindescplot <- maindescplot$rdplot + geom_point(rddset[abs(rddset$minorityprimarymargin) <= bandwidth], mapping=aes(minorityprimarymargin, !!outcomevar), size=1.1, col="darkgray", alpha=.5)
  return(maindescplot)
}

rddset[,uncontestedgeneral:=0];rddset[uncontestedgen==1,uncontestedgeneral:=1]
covunc <- rdplotllfunc(rddset$uncontestedgeneral, "uncontestedgeneral", "Uncontested General", "RD Plot: Uncontested General Election", c(0,1))
pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/uncontestedgeneral_plot_withscatter.pdf")
covunc
dev.off()

# Figure A3 ----
pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/RDdensity_histogram_combineddata.pdf")
hist(rddset$minorityprimarymargin, breaks=50, main="Histogram of Running Variable (Minority Primary Win Margin)") #also just make a histogram
dev.off()

# Figure A4 ----
rddset$Republicandist <- ifelse(rddset$party=="Republican" ,1,0); table(rddset$Republicandist) 

rdplot(rddset$Total.x, rddset$minorityprimarymargin)
rdplot(rddset$pctWhite, rddset$minorityprimarymargin)
rdplot(rddset$pctBlack, rddset$minorityprimarymargin)
rdplot(rddset$pctLatino, rddset$minorityprimarymargin)
rdplot(rddset$pctAsian, rddset$minorityprimarymargin)
rdplot(rddset$openseat, rddset$minorityprimarymargin)
rdplot(rddset$Dem_2pyShare, rddset$minorityprimarymargin)
rdplot(rddset$Republicandist, rddset$minorityprimarymargin)
rdplot(rddset$Upper.x, rddset$minorityprimarymargin)

bandwidth = rdrobust(rddset$Total.x, rddset$minorityprimarymargin)$bws[1, 1]
xlim = ceiling(bandwidth)
rdplot(rddset$Total.x[abs(rddset$minorityprimarymargin) <= bandwidth], rddset$minorityprimarymargin[abs(rddset$minorityprimarymargin) <= bandwidth],
       p = 1, kernel = "triangular")

covpctw <- rdplotllfunc(rddset$pctWhite, "pctWhite", "Percent White", "RD Plot: District Pct. White", c(0,1))
covpctb <- rdplotllfunc(rddset$pctBlack, "pctBlack","Percent Black", "RD Plot: District Pct. Black", c(0,1))
covpctl <- rdplotllfunc(rddset$pctLatino, "pctLatino", "Percent Latino", "RD Plot: District Pct. Latino", c(0,1))
covpcta <- rdplotllfunc(rddset$pctAsian, "pctAsian","Percent Asian", "RD Plot: District Pct. Asian", c(0,1))
covtotp <- rdplotllfunc(rddset$Total.x, "Total.x", "Total Population", "RD Plot: Total Population", c(0,200000))
covopen <- rdplotllfunc(rddset$openseat, "openseat", "Proportion Open Seat Races", "RD Plot: Open Seat Race (0/1)", c(0,1))
covrepd <- rdplotllfunc(rddset$Republicandist, "Republicandist", "Proportion Republican Primaries", "RD Plot: R Primary (0/1)", c(0,1))
covdemp <- rdplotllfunc(rddset$Dem_2pyShare, "Dem_2pyShare", "District Democratic (2party) Presidential Voteshare 2016", "RD Plot: Dem Voteshare 2016", c(0,1))
covuppr <- rdplotllfunc(rddset$Upper.x, "Upper.x", "Proportion Upper-Chamber Districts", "RD Plot: Upper Chamber (0/1)", c(0,1))
dev.off()

pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/backgroundcovariates_panelplot_withscatter.pdf", height=12, width=12)

grid.arrange(covpctw, covpctb, covpctl, covpcta, covtotp, covopen, covrepd,covdemp, covuppr, nrow = 3)
dev.off()

# Figure A5 ----
#blogpost here: https://www.r-bloggers.com/2019/04/11264-regressions-in-one-tidy-plot/
#paper about spec curves here: https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2694998
#see vignette here: https://joachim-gassen.github.io/rdfanalysis/articles/analyzing_rdf.html
# devtools::install_github("joachim-gassen/rdfanalysis")
library(rdfanalysis)

setDT(rddset)
subsets <- list(rddset, rddset[year.x==2018,], rddset[year.x==2020,], rddset[is.na(rddset$mmd2keep)==T,])
subsetnames <- c("all", "Only2018", "Only2020", "DropMMDs") 
subsets <- list(rddset, rddset[is.na(rddset$mmd2keep)==T,])
subsetnames <- c("all", "DropMMDs")

bandwidthselections <- c("mserd", "msetwo", "msesum", "msecomb1", "msecomb2", "cerrd", "certwo", "cersum", "cercomb1", "cercomb2") #everything in the package

polynomials <- c(1:5)

kernels <- c("triangular", "epanechnikov", "uniform")

covariates <- c("None", "Included")

estimates <- c("Bias-corrected", "Conventional")

spectab <- as.data.frame(matrix(NA, nrow=length(subsets)*length(bandwidthselections)*length(polynomials)*length(kernels)*length(covariates)*length(estimates), ncol=3+6)) #set up storage (width=3+number of loops)

rownumbase=1 #initialize row number for storage
outcomevar = "general2p"
for (j in 1:length(subsets)){ #subsets of the data
  dataset <- as.data.frame(subsets[j])	
  for (k in 1:length(bandwidthselections)){ #various bandwidth selection approaches
    bwselect = bandwidthselections[k]
    print(bwselect)
    for (l in 1:length(polynomials)){ #polynomial order
      order = polynomials[l]
      for(m in 1:length(kernels)){ #which kernel
        kernel=kernels[m]	
        for (o in 1:length(covariates)){ #include covars or no
          covvalue <- covariates[o]
          if(covvalue == "None"){ 			
            rddmod <- rdrobust(dataset[,outcomevar], dataset$minorityprimarymargin, p=order, bwselect=bwselect, kernel=kernel)}
          if(covvalue == "Included"){ 			
            rddmod <- rdrobust(dataset[,outcomevar], dataset$minorityprimarymargin, p=order, bwselect=bwselect, kernel=kernel, covs=cbind(dataset$Total.x, dataset$partyfac, dataset$openseat, dataset$partyvotesharepres))} 
          for (p in 1:length(estimates)){
            type <- estimates[p]
            coeffslot <- ifelse(type == "Bias-corrected", 3, 1) #pull either bias-corrected or not 
            spectab[(rownumbase), ] <- c(rddmod$coef[1], rddmod$ci[coeffslot,], subsetnames[j], covariates[o], bandwidthselections[k], polynomials[l], kernels[m], estimates[p]) #save results and specs
            print((rownumbase))
            rownumbase = rownumbase+1 #increment row numbers so we know where to store results
          }}}}}}

colnames(spectab) <- c("est", "lb", "ub", "subsetchoice", "covariates", "bwselection", "polynomialorder", "kernel", "SE")
ests <- spectab
ests$est <- as.numeric(ests$est)
ests$lb <- as.numeric(ests$lb)
ests$ub <- as.numeric(ests$ub)
attr(ests, "choices") <- 4:9

pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/rdf_spec_curve_main.pdf")
plot_rdf_spec_curve(ests, "est", "lb", "ub") 
dev.off()

# Figure A6 ----

## left
summary(rdrobust(rddset$incumbentwins, rddset$minorityprimarymargin))
pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/RDDplot_incumbentnominated_mechanisms_combineddata.pdf")
rdplot(rddset$incumbentwins, rddset$minorityprimarymargin, y.lim=c(0,1), x.label="Primary Win Margin for Minority Candidate", y.label="Party's nominee is the seat's incumbent")
dev.off()

## right
summary(rdrobust(rddset$womanwins, rddset$minorityprimarymargin))
pdf("~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Figures/RDDplot_womannominated_mechanisms_combineddata.pdf")
rdplot(rddset$womanwins, rddset$minorityprimarymargin, y.lim=c(0,1), x.label="Primary Win Margin for Minority Candidate", y.label="Party's nominee is a woman")
dev.off()

# Table A1 ----
rddsetcomplete <- rddset[is.na(rddset$minorityprimarymargin)==F & is.na(rddset$general2p)==F,]; dim(rddsetcomplete)
totalstab_comp <- table(rddsetcomplete$year.x, rddsetcomplete$party)
print(xtable(totalstab_comp, caption="Election counts", label="electioncountscomplete"), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/counts_table_20182020combineddatacompletecases.tex", include.rownames=TRUE)

# Table A2 ----
rddset_republicans <- rddset[rddset$party=="Republican",]; dim(rddset_republicans)
basicrddrep <- rdrobust(rddset_republicans$general2p, rddset_republicans$minorityprimarymargin)
basicrddrep_covar <- rdrobust(rddset_republicans$general2p, rddset_republicans$minorityprimarymargin, covs=cbind(rddset_republicans$partyfac,rddset_republicans$openseat, rddset_republicans$Total.x, rddset_republicans$partyvotesharepres))

basicrddrepp3 <- rdrobust(rddset_republicans$general2p, rddset_republicans$minorityprimarymargin, p=3, covs=cbind(rddset_republicans$partyfac,rddset_republicans$openseat, rddset_republicans$Total.x, rddset_republicans$partyvotesharepres))

summary(basicrddrep)
summary(basicrddrep_covar)
summary(basicrddrepp3)

model1 <- c(round(basicrddrep$coef[1], 2), paste("(",round(basicrddrep$ci[3],2),",",round(basicrddrep$ci[6],2), ")", sep=""), "p=1", "", sum(basicrddrep$N_h), round(basicrddrep$bws[1],2))
model2 <- c(round(basicrddrep_covar$coef[1],2), paste("(",round(basicrddrep_covar$ci[3],2),",",round(basicrddrep_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrddrep_covar$N_h), round(basicrddrep_covar$bws[1],2))
model3 <- c(round(basicrddrepp3$coef[1],2), paste("(",round(basicrddrepp3$ci[3],2),",",round(basicrddrepp3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddrepp3$N_h), round(basicrddrepp3$bws[1],2))

modtab <- cbind(model1, model2, model3)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth")

print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare, Republican primaries only", label="mainRDtab_rep", align="rccc"), include.colnames=F, hline.after = c(0,2,6), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/simplemainRDtable_Republicans.tex")

# Table A3 ----
basicrddalt <- rdrobust(rddset$general2palt, rddset$minorityprimarymargin)
basicrddalt_covar <- rdrobust(rddset$general2palt, rddset$minorityprimarymargin, covs=cbind(rddset$partyfac,rddset$openseat, rddset$Total.x, rddset$partyvotesharepres))
basicrddaltp3 <- rdrobust(rddset$general2palt, rddset$minorityprimarymargin, p=3, covs=cbind(rddset$partyfac,rddset$openseat, rddset$Total.x, rddset$partyvotesharepres))

summary(basicrddalt)
summary(basicrddalt_covar)
summary(basicrddaltp3)

model1 <- c(round(basicrddalt$coef[1], 2), paste("(",round(basicrddalt$ci[3],2),",",round(basicrddalt$ci[6],2), ")", sep=""), "p=1", "", sum(basicrddalt$N_h), round(basicrddalt$bws[1],2))
model2 <- c(round(basicrddalt_covar$coef[1],2), paste("(",round(basicrddalt_covar$ci[3],2),",",round(basicrddalt_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrddalt_covar$N_h), round(basicrddalt_covar$bws[1],2))
model3 <- c(round(basicrddaltp3$coef[1],2), paste("(",round(basicrddaltp3$ci[3],2),",",round(basicrddaltp3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddaltp3$N_h), round(basicrddaltp3$bws[1],2))

modtab <- cbind(model1, model2, model3)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth")

print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare, with alternative voteshare measure", label="mainRDtab_alt", align="rccc"), include.colnames=F, hline.after = c(0,2,6), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/simplemainRDtable_presvote_includinguncontested.tex")

# Table A4 ----
rddset_safeseats <- rddset[rddset$partyvotesharepres <.4 | rddset$partyvotesharepres >.6,]; dim(rddset_safeseats)
basicrddsafe <- rdrobust(rddset_safeseats$general2p, rddset_safeseats$minorityprimarymargin)
basicrddsafe_covar <- rdrobust(rddset_safeseats$general2p, rddset_safeseats$minorityprimarymargin, covs=cbind(rddset_safeseats$partyfac, rddset_safeseats$Total.x, rddset_safeseats$openseat))

basicrddsafep3 <- rdrobust(rddset_safeseats$general2p, rddset_safeseats$minorityprimarymargin, p=3, covs=cbind(rddset_safeseats$partyfac, rddset_safeseats$Total.x, rddset_safeseats$openseat))

summary(basicrddsafe)
summary(basicrddsafe_covar)
summary(basicrddsafep3)

# show CI rather than SE
model1 <- c(round(basicrddsafe$coef[1], 2), paste("(",round(basicrddsafe$ci[3],2),",",round(basicrddsafe$ci[6],2), ")", sep=""), "p=1", "", sum(basicrddsafe$N_h), round(basicrddsafe$bws[1],2))
model2 <- c(round(basicrddsafe_covar$coef[1],2), paste("(",round(basicrddsafe_covar$ci[3],2),",",round(basicrddsafe_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrddsafe_covar$N_h), round(basicrddsafe_covar$bws[1],2))
model3 <- c(round(basicrddsafep3$coef[1],2), paste("(",round(basicrddsafep3$ci[3],2),",",round(basicrddsafep3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddsafep3$N_h), round(basicrddsafep3$bws[1],2))

modtab <- cbind(model1, model2, model3)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth")

print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare, Safe-seat races only", label="mainRDtab_open", align="rccc"), include.colnames=F, hline.after = c(0,2,6), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/simplemainRDtable_safeseats.tex")

# Table A5 ----
rddset_b <- rddset[rddset$RDDBlack==1,]; dim(rddset_b)
basicrddb <- rdrobust(rddset_b$general2p, rddset_b$minorityprimarymargin)
basicrddb_covar <- rdrobust(rddset_b$general2p, rddset_b$minorityprimarymargin, covs=cbind(rddset_b$partyfac,rddset_b$openseat, rddset_b$Total.x, rddset_b$partyvotesharepres))

basicrddbp3 <- rdrobust(rddset_b$general2p, rddset_b$minorityprimarymargin, p=3, covs=cbind(rddset_b$partyfac,rddset_b$openseat, rddset_b$Total.x, rddset_b$partyvotesharepres))

summary(basicrddb)
summary(basicrddb_covar)
summary(basicrddbp3)

model1 <- c(round(basicrddb$coef[1], 2), paste("(",round(basicrddb$ci[3],2),",",round(basicrddb$ci[6],2), ")", sep=""), "p=1", "", sum(basicrddb$N_h), round(basicrddb$bws[1],2))
model2 <- c(round(basicrddb_covar$coef[1],2), paste("(",round(basicrddb_covar$ci[3],2),",",round(basicrddb_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrddb_covar$N_h), round(basicrddb_covar$bws[1],2))
model3 <- c(round(basicrddbp3$coef[1],2), paste("(",round(basicrddbp3$ci[3],2),",",round(basicrddbp3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddbp3$N_h), round(basicrddbp3$bws[1],2))

modtab <- cbind(model1, model2, model3)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth")

print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare, Black-White matchups only", label="mainRDtab_Black", align="rccc"), include.colnames=F, hline.after = c(0,2,6), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/simplemainRDtable_BWonly.tex")

# Table A6 ----
rddset_l <- rddset[rddset$RDDLatino==1,]; dim(rddset_l)
basicrddl <- rdrobust(rddset_l$general2p, rddset_l$minorityprimarymargin)
basicrddl_covar <- rdrobust(rddset_l$general2p, rddset_l$minorityprimarymargin, covs=cbind(rddset_l$partyfac,rddset_l$openseat, rddset_l$Total.x, rddset_l$partyvotesharepres))

basicrddlp3 <- rdrobust(rddset_l$general2p, rddset_l$minorityprimarymargin, p=3, covs=cbind(rddset_l$partyfac,rddset_l$openseat, rddset_l$Total.x, rddset_l$partyvotesharepres))

summary(basicrddl)
summary(basicrddl_covar)
summary(basicrddlp3)

model1 <- c(round(basicrddl$coef[1], 2), paste("(",round(basicrddl$ci[3],2),",",round(basicrddl$ci[6],2), ")", sep=""), "p=1", "", sum(basicrddl$N_h), round(basicrddl$bws[1],2))
model2 <- c(round(basicrddl_covar$coef[1],2), paste("(",round(basicrddl_covar$ci[3],2),",",round(basicrddl_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrddl_covar$N_h), round(basicrddl_covar$bws[1],2))
model3 <- c(round(basicrddlp3$coef[1],2), paste("(",round(basicrddlp3$ci[3],2),",",round(basicrddlp3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddlp3$N_h), round(basicrddlp3$bws[1],2))

modtab <- cbind(model1, model2, model3)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth")

print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare, Latino-White matchups only", label="mainRDtab_Latino", align="rccc"), include.colnames=F, hline.after = c(0,2,6), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/simplemainRDtable_LWonly.tex")

# Table A7 ----
rddset_a <- rddset[rddset$RDDAsian==1,]; dim(rddset_a)
basicrdda <- rdrobust(rddset_a$general2p, rddset_a$minorityprimarymargin)
basicrdda_covar <- rdrobust(rddset_a$general2p, rddset_a$minorityprimarymargin, covs=cbind(rddset_a$partyfac,rddset_a$openseat, rddset_a$Total.x, rddset_a$partyvotesharepres))
basicrddap3 <- rdrobust(rddset_a$general2p, rddset_a$minorityprimarymargin, p=3, covs=cbind(rddset_a$partyfac,rddset_a$openseat, rddset_a$Total.x, rddset_a$partyvotesharepres))

summary(basicrdda)
summary(basicrdda_covar)
summary(basicrddap3)

model1 <- c(round(basicrdda$coef[1], 2), paste("(",round(basicrdda$ci[3],2),",",round(basicrdda$ci[6],2), ")", sep=""), "p=1", "", sum(basicrdda$N_h), round(basicrdda$bws[1],2))
model2 <- c(round(basicrdda_covar$coef[1],2), paste("(",round(basicrdda_covar$ci[3],2),",",round(basicrdda_covar$ci[6],2), ")", sep=""), "p=1", "X", sum(basicrdda_covar$N_h), round(basicrdda_covar$bws[1],2))
model3 <- c(round(basicrddap3$coef[1],2), paste("(",round(basicrddap3$ci[3],2),",",round(basicrddap3$ci[6],2), ")", sep=""), "p=3", "X",sum(basicrddap3$N_h), round(basicrddap3$bws[1],2))

modtab <- cbind(model1, model2, model3)
rownames(modtab) <- c("Minority nominee", "", "Polynomial", "Covariates", "Effective Sample Size", "Bandwidth")

print(xtable(modtab, caption="RDD Estimates of the Effect of Nominating a Minority Candidate on General-Election Voteshare, Asian-White matchups only", label="mainRDtab_Asian", align="rccc"), include.colnames=F, hline.after = c(0,2,6), file="~/Dropbox (MIT)/RDD_stateleg/Replication Materials/Appendix Tables and Figures/Tables/simplemainRDtable_AWonly.tex")



